import MyCard from '@/components/MyCard';
import MyPageContainer from '@/components/MyPageContainer';
import {
  getOrderInfoVoByIdUsingGet,
  updateExpiredOrderInfoUsingPost,
} from '@/services/backend/orderInfoController';
import { getServiceProjectVoByIdUsingGet } from '@/services/backend/serviceProjectController';
import { convertCentsToYuan } from '@/utils/moneyUtils';
import { AlipayOutlined, PropertySafetyOutlined, WechatOutlined } from '@ant-design/icons';
import { Button, Card, Flex, Image, message, QRCode, Space, Tag, Typography } from 'antd';
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';

/**
 * 处理过期订单
 */
const handleExpired = async (orderInfoId: number) => {
  try {
    const res = await updateExpiredOrderInfoUsingPost({
      id: orderInfoId,
    });
    if (res.code === 0) {
      message.warning('订单已超时，请重新下单');
    }
  } catch (e: any) {
    message.error(e.message);
  }
};

const ServiceProjectOrder: React.FC = () => {
  const params = useParams();
  const id = (params['id'] ?? -1) as number;
  const [orderInfo, setOrderInfo] = useState<API.OrderInfoVO>();
  const [serviceProject, setServiceProject] = useState<API.ServiceProjectVO>();
  const [loading, setLoading] = useState<boolean>(true);
  const [payMethod, setPayMethod] = useState<'wechat' | 'alipay' | 'other'>('wechat'); // 默认选择微信支付
  const [countdown, setCountdown] = useState<{ minutes: number; seconds: number }>({
    minutes: 15,
    seconds: 0,
  });
  const [isExpired, setIsExpired] = useState<boolean>(false);

  // 计算剩余时间
  const calculateTimeLeft = (createTime: string) => {
    const orderTime = new Date(createTime).getTime();
    const currentTime = new Date().getTime();
    const expiryTime = orderTime + 15 * 60 * 1000; // 15分钟后过期

    // 计算剩余毫秒数
    const timeLeft = expiryTime - currentTime;

    if (timeLeft <= 0) {
      return { minutes: 0, seconds: 0 };
    }

    // 转换为分钟和秒
    const minutes = Math.floor(timeLeft / (1000 * 60));
    const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);

    return { minutes, seconds };
  };

  // 初始化倒计时
  useEffect(() => {
    if (orderInfo?.createTime) {
      const timeLeft = calculateTimeLeft(orderInfo.createTime);
      setCountdown(timeLeft);

      if (timeLeft.minutes === 0 && timeLeft.seconds === 0) {
        setIsExpired(true);
      }
    }
  }, [orderInfo]);

  // 倒计时逻辑
  useEffect(() => {
    if (!orderInfo?.createTime || isExpired) return;

    const timer = setInterval(() => {
      if (countdown.seconds > 0) {
        setCountdown({ ...countdown, seconds: countdown.seconds - 1 });
      } else if (countdown.minutes > 0) {
        setCountdown({ minutes: countdown.minutes - 1, seconds: 59 });
      } else {
        clearInterval(timer);
        setIsExpired(true);
        //处理过期订单
        handleExpired(id);
      }
    }, 1000);

    return () => clearInterval(timer);
  }, [orderInfo, isExpired]);

  //初始化
  useEffect(() => {
    setLoading(true);
    //获取订单信息 and 下单的项目信息
    getOrderInfoVoByIdUsingGet({ id: id })
      .then((res) => {
        if (res.code === 0 && res.data) {
          setOrderInfo(res.data);
          return getServiceProjectVoByIdUsingGet({ id: res.data.targetId });
        }
      })
      .then((res1) => {
        if (res1 && res1.code === 0 && res1.data) {
          setServiceProject(res1.data);
        }
      })
      .catch((e: any) => {
        message.error(e.message);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  const content: React.ReactNode = (
    <>
      <MyCard
        title={`订单编号：${orderInfo?.orderNo}`}
        extra={
          <div>
            <Flex align="center" justify="center" gap="middle">
              <Typography.Text
                style={{
                  fontSize: '18px',
                  color: isExpired ? '#ff4d4f' : '#000000',
                }}
              >
                {isExpired ? (
                  '订单已超时，请重新下单'
                ) : (
                  <>
                    订单有效期还剩：{String(countdown.minutes).padStart(2, '0')}:
                    {String(countdown.seconds).padStart(2, '0')}
                  </>
                )}
              </Typography.Text>
            </Flex>
          </div>
        }
      >
        <Card variant={'borderless'} className={'bg-gray-100'}>
          <Flex>
            <div id={'cover'}>
              <a
                href={`/serviceProject/detail/${serviceProject?.id}`}
                target={'_blank'}
                rel="noreferrer"
              >
                <Image
                  src={serviceProject?.cover}
                  width={160}
                  preview={false}
                  className={'rounded-lg'}
                />
              </a>
            </div>
            <Flex
              id={'introduce'}
              vertical={true}
              className={'m-4'}
              justify={'space-around'}
              flex={'1'}
              wrap
            >
              <span>
                <Typography.Title level={5}>{serviceProject?.title}</Typography.Title>
              </span>
              <span className={'text-base'}>
                订单内容：
                <Space size={4}>
                  {orderInfo?.needCode ? (
                    <Tag bordered={false} color={'green'}>
                      项目源码
                    </Tag>
                  ) : (
                    <></>
                  )}
                  {orderInfo?.needDoc ? (
                    <Tag bordered={false} color={'blue'}>
                      系统设计文档
                    </Tag>
                  ) : (
                    <></>
                  )}
                  {orderInfo?.needDeploy ? (
                    <Tag bordered={false} color={'pink'}>
                      远程部署
                    </Tag>
                  ) : (
                    <></>
                  )}
                </Space>
              </span>
            </Flex>
            <Flex id={'amount'} align={'center'}>
              <span>实付金额：</span>
              <span className={'text-[#ff4d4f] text-2xl font-medium'}>
                {convertCentsToYuan(orderInfo?.amount ?? 0)}
              </span>
            </Flex>
          </Flex>
        </Card>
      </MyCard>
      <div className={'mt-4'}>
        <Flex justify="start" gap="large" className="py-4">
          <Card
            hoverable
            className="w-64 text-center cursor-pointer border-2"
            style={{
              borderColor: payMethod === 'wechat' ? '#BFE6FF' : 'transparent',
              backgroundColor: payMethod === 'wechat' ? '#F0F9FF' : 'white',
            }}
            onClick={() => setPayMethod('wechat')}
          >
            <Flex align="center" gap="middle">
              <div className="w-12 h-12 flex items-center justify-center bg-[#07C160] rounded-full">
                <WechatOutlined className="text-white text-xl" />
              </div>
              <Typography.Text strong>微信支付</Typography.Text>
            </Flex>
          </Card>
          <Card
            hoverable
            className="w-64 text-center cursor-pointer border-2"
            style={{
              borderColor: payMethod === 'alipay' ? '#BFE6FF' : 'transparent',
              backgroundColor: payMethod === 'alipay' ? '#F0F9FF' : 'white',
            }}
            onClick={() => {
              message.warning('支付宝支付暂未开放');
              setPayMethod('wechat');
            }}
          >
            <Flex align="center" gap="middle">
              <div className="w-12 h-12 flex items-center justify-center bg-[#1677FF] rounded-full">
                <AlipayOutlined className="text-white text-xl" />
              </div>
              <Typography.Text strong>支付宝支付</Typography.Text>
            </Flex>
          </Card>
          <Card
            hoverable
            className="w-64 text-center cursor-pointer border-2"
            style={{
              borderColor: payMethod === 'other' ? '#BFE6FF' : 'transparent',
              backgroundColor: payMethod === 'other' ? '#F0F9FF' : 'white',
            }}
            onClick={() => {
              message.warning('其它支付方式暂未开放');
              setPayMethod('wechat');
            }}
          >
            <Flex align="center" gap="middle">
              <div className="w-12 h-12 flex items-center justify-center bg-[#FF9900] rounded-full">
                <PropertySafetyOutlined className="text-white text-xl" />
              </div>
              <Typography.Text strong>其它支付</Typography.Text>
            </Flex>
          </Card>
        </Flex>
      </div>
      <div className="mt-4">
        <Flex vertical align="center" className="py-6">
          <QRCode type="svg" value={'-'} size={200} status={isExpired ? 'expired' : 'active'} />
          <Typography.Text type="secondary" className="mb-4">
            请使用{payMethod === 'wechat' ? '微信' : '支付宝'}扫描二维码完成支付
          </Typography.Text>
          <Button type="primary" size="large" className="mb-2" disabled={isExpired}>
            我已完成支付
          </Button>
          <Typography.Link className="text-sm">遇到问题？联系客服</Typography.Link>
        </Flex>
      </div>
    </>
  );

  return <MyPageContainer content={content} loading={loading} />;
};

export default ServiceProjectOrder;
